<template>
  <j-modal
    :title="'报表上报'"
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :ok-button-props="{ props: { disabled: disableSubmit } }"
    :fullscreen="true"
    @close="close"
    cancelText="关闭"
  >
    <template slot="footer">
      <a-button key="back" style="padding-left: 8px; padding-right: 8px" @click="close(false)"> 关闭</a-button>
      <a-popconfirm :disabled="disableSubmit" title="确定保存吗?" @confirm="() => saveOrSubmit('save', null)">
        <a-button key="save" style="padding-left: 8px; padding-right: 8px" :disabled="disableSubmit"> 保存</a-button>
      </a-popconfirm>
      <a-button
        key="submit"
        type="primary"
        style="padding-left: 8px; padding-right: 8px"
        :disabled="disableSubmit"
        @click="close(true)"
      >
        提交审批
      </a-button>
    </template>
    <div :class="{ isCheck: isCheck }">
      <!-- <div class="table-header">
        <span class="table-title">填报单位：</span>{{ model.departName }} <span class="table-title">审计负责人：</span
        >{{ model.auditPersonName }} <span class="table-title">填表人：</span>{{ model.createByText }}
        <span class="table-title">填表时间：</span>{{ model.createTime }} <span class="table-title">统计时间：</span
        >{{ model.year }}年（{{ model.quarter }}季度）
      </div> -->
      <a-table
        class="edit-list"
        ref="table"
        size="middle"
        bordered
        rowKey="xu"
        width="100vw"
        :pagination="false"
        :columns="columns"
        :dataSource="dataSource"
        :scroll="{ x: 250, y: '70vh' }"
      >
        <!-- 表头 -->
        <div slot="title">
          <div class="title">{{ title }}</div>
          <div class="sub-title">
            <div>填报单位：{{ model.departName }}</div>
            <div>{{ model.year }}年（{{ model.quarter }}季）度</div>
            <div>审计负责人：
              <fzrSelect :disabled="disableSubmit" v-model="model.head"></fzrSelect>
            </div>
            <div>填表人：{{ model.createByText }}</div>
            <div>填表时间：{{ model.createTime }}</div>
            <div>金额单位（万元）</div>
          </div>
        </div>
        <span v-if="!disableSubmit" slot="actionName">
          <a-button @click="addTableList" style="padding: 0 5px" size="small" type="primary" icon="plus">新增</a-button>
        </span>
        <template v-for="col in customRenderList" v-slot:[col]="text, record, index">
          <div :key="col" v-if="(col == 'traffic' || col == 'stay' || col == 'business') && !(record.xu == '合计')">
            <a-input-number
              v-if="!disableSubmit"
              class="inputnumber"
              :key="col"
              :precision="2"
              :disabled="disableSubmit"
              @change="handleChange(record, col)"
              v-model="record[col]"
            />
            <span v-else>{{ record[col] }}</span>
          </div>
          <div :key="col" v-else-if="record.xu == '合计'">
            {{ record[col] }}
          </div>
          <div :key="col" v-else>
            <a-input
              class="noborderInput"
              v-if="!disableSubmit"
              :key="col"
              :disabled="disableSubmit"
              @change="handleChange(record, col)"
              v-model="record[col]"
            />
            <span v-else>{{ record[col] }}</span>
          </div>
        </template>
        <span v-if="!disableSubmit" slot="action" slot-scope="text, record, index">
          <a v-if="record.xu != '合计'" @click="deleteTableList(record, index)">删除</a>
        </span>
      </a-table>
      <div class="uploadFile" style="height: 40px; line-height: 40px; position: relative; margin-top: 10px; width: 97vw">
        <span style="font-size: 16px" v-if="disableSubmit">说明性文件:</span>
        <ZUpload
          style="position: absolute; left: 120px; width: 92%"
          :disabled="disableSubmit"
          :isShow="disableSubmit"
          ref="fileUpload"
          :fileid="model.fileId"
          @uploadFile="saveData"
          :isScroll="true"
        ></ZUpload>
      </div>
    </div>

    <SelectApprove ref="approver" @submitData="saveOrSubmit"></SelectApprove>
  </j-modal>
</template>
<script>
  import {deleteAction, getAction, postAction} from '@/api/manage'
  import columns from './columns6'
  import store from '@/store/'
  import ZUpload from '../../../components/ZUpload'
  import SelectApprove from '../SelectApprover'
  import fzrSelect from '../fzrSelect'
  import pubMothod from './PublicMethod'

  export default {
    name: 'ModelView6',
    components: {
      SelectApprove,
      ZUpload,
      fzrSelect
    },
    data() {
      return {
        userInfo: store.getters.userInfo,
        departInfo: store.getters.departInfo,
        disableSubmit: false,
        columns: [],
        dataSource: [],
        title: '',
        model: {},
        visible: false,
        isCheck: false,
        officeId: '',
        btnStyle: 'save',
        approveId: '',
        customRenderList: ['name', 'time', 'traffic', 'stay', 'business'],
        url: {
          list: '/sjxxzhbb/sjAuditInfo/queryAuditoCostInfoById',
          save: '/sjxxzhbb/sjAuditInfo/saveCostInfo',
          delete: '/sjxxzhbb/sjAuditInfo/remove',
          submitData: '/common/sjProcCommon/costShen',
        },
      }
    },
    created() {
      this.dataSource.push()
    },
    methods: {
      handleChange(row, col) {
        if (col === 'traffic' || col === 'stay' || col === 'business') {
          if (row[col] == '' || row[col] == null || row[col] == undefined) {
            row[col] = 0
          }
          row['subtotal'] =
            parseFloat(row['traffic'] || '0') + parseFloat(row['stay'] || '0') + parseFloat(row['business'] || '0')
          this.setHj(col)
        }
      },
      setHj(col) {
        let rows = this.dataSource.length - 1
        let num = 0
        let hjNum = 0
        for (let i = 0; i < rows; i++) {
          num = num + parseFloat(this.dataSource[i][col] || '0')
          hjNum = hjNum + parseFloat(this.dataSource[i]['subtotal'] || '0')
        }
        this.dataSource[rows][col] = num
        this.dataSource[rows]['subtotal'] = hjNum
      },
      add(record) {
        this.model = Object.assign({}, record)
        this.columns = columns(this)
        this.visible = true
        this.setReportTitle()
        this.model.fileId = ''
        this.dataSource = [
          {
            xu: 1,
            name: '',
            time: '',
            traffic: 0,
            stay: 0,
            business: 0,
            subtotal: 0,
          },
          {
            xu: '合计',
            name: null,
            time: null,
            traffic: 0,
            stay: 0,
            business: 0,
            subtotal: 0,
          },
        ]
      },
      check(record) {
        this.model.id = record.id
        this.columns = columns(this).slice(0, columns(this).length - 1)
        this.visible = true
        this.getTableData()
      },
      edit(record) {
        this.columns = columns(this)
        this.model.id = record.id
        this.visible = true
        this.getTableData()
      },
      setReportTitle() {
        let nowDate = new Date()
        this.model.createTime = pubMothod.dateFormat('yyyy-MM-dd hh:mm:ss', nowDate)
        this.model.addtime = parseInt(Number(nowDate.getTime()) / 1000)
        this.model.createByText = this.userInfo.realname
        this.model.head = ''
        this.model.departName = this.departInfo.departName
        this.model.createBy = this.userInfo.id
        this.model.officeId = this.departInfo.id
      },
      getTableData() {
        getAction(this.url.list, {
          id: this.model.id,
          sjType: '4',
        }).then((res) => {
          if (res.success && res.result) {
            this.officeId = res.result[0].officeId
            this.dataSource = JSON.parse(res.result[0].info)
            this.model.createTime = res.result[0].createTime
            this.model.createByText = res.result[0].createByText
            this.model.head = res.result[0].head
            this.model.departName = res.result[0].departName
            this.model.year = res.result[0].year
            this.model.quarter = res.result[0].quarter
            this.model.fileId = res.result[0].fileId
            this.Loading = false
          } else {
            this.$message.error(res.message)
            this.Loading = false
          }
        })
      },
      close(isSubmit) {
        if (isSubmit) {
          this.$refs.approver.showApproveConfirm = true
        } else {
          this.dataSource = []
          this.visible = false
        }
      },
      // 保存或提交
      saveOrSubmit(style, approveId) {
        this.btnStyle = style
        this.approveId = approveId
        this.$refs.fileUpload.saveFile('cdsjryfytjb')
      },
      // 保存数据
      saveData(id) {
        this.Loading = true
        let string = JSON.stringify(this.dataSource)
        let param = {
          fileId: id,
          info: string,
          year: this.model.year,
          quarter: this.model.quarter,
          sjType: '4',
          head: this.model.head,
          addtime: this.model.addtime,
          officeId: this.model.officeId,
        }
        if (this.model.id) {
          param.id = this.model.id
        }
        postAction(this.url.save, param).then((res) => {
          if (res.success) {
            if (!this.model.id) {
              this.model.id = res.result
            }
            if (this.btnStyle == 'save') {
              this.$message.success(res.message)
              this.Loading = false
              this.visible = false
              this.$emit('ok')
              return
            } else {
              this.submitData(this.approveId)
            }
          } else {
            this.$message.error(res.message)
            console.log(res)
          }
        })
      },
      // 提交数据
      submitData(userId) {
        getAction(this.url.submitData, {
          proId: this.model.id,
          userIds: userId,
          reportInfo: JSON.stringify(this.dataSource),
          type: '4',
          sjType: '4',
          state: '1',
        }).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.Loading = false
            this.visible = false
            this.$emit('ok')
          } else {
            this.$message.error(res.message)
            console.log(res)
          }
        })
      },
      // 新增弹窗
      addTableList() {
        let num = 1
        this.dataSource.forEach((item, index) => {
          if (item.xu != '合计') {
            item.xu = num++
          }
        })
        this.dataSource.splice(-1, 0, {
          xu: this.dataSource.length,
          name: '',
          time: '',
          traffic: 0,
          stay: 0,
          business: 0,
          subtotal: 0,
        })
      },
      delete(record) {
        deleteAction(this.url.delete, {id: record.id}).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.$emit('ok')
          } else {
            this.$message.error(res.message)
          }
        })
      },
      deleteTableList(row, index) {
        let num = 1
        let recordData = this.dataSource[this.dataSource.length - 1]
        let traffic = parseFloat(row['traffic'] || '0')
        let stay = parseFloat(row['stay'] || '0')
        let business = parseFloat(row['business'] || '0')
        let subtotal = parseFloat(row['subtotal'] || '0')
        recordData['traffic'] = parseFloat(recordData['traffic'] || '0') - traffic
        recordData['stay'] = parseFloat(recordData['stay'] || '0') - stay
        recordData['business'] = parseFloat(recordData['business'] || '0') - business
        recordData['subtotal'] = parseFloat(recordData['subtotal'] || '0') - subtotal
        this.dataSource.splice(index, 1)
        this.dataSource.forEach((item, index) => {
          if (item.xu != '合计') {
            item.xu = num++
          }
        })
      },
    },
  }
</script>

<style lang="less" scoped>
  // @import '../../../css/checkAndEdit.less';
  @import '../../css/baobiaotable.less';

  .table-header {
    margin-bottom: 10px;

    .table-title {
      font-weight: bold;
      margin-left: 15px;
    }
  }

  .edit-list {
    .noborderInput {
      border: 0;
      padding: 0px 0px;
    }
  }
</style>
